﻿using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace Common.Swagger.Filter
{
    /// <summary>
    /// 敏感数据处理（参数）
    /// </summary>
    public class SensitiveDataParameterFilter : IParameterFilter
    {
        public void Apply(OpenApiParameter parameter, ParameterFilterContext context)
        {
            Type type = null;
            List<string> attr = new List<string>();
            if (context.PropertyInfo != null)
            {
                //当为实体属性时取属性信息
                type = context.PropertyInfo.PropertyType;
                attr = context.PropertyInfo.GetCustomAttributes(true).Select(s => s.GetType().Name).ToList();
            }
            else
            {
                //直接传参数不为实体时
                type = context.ParameterInfo.ParameterType;
                attr = context.ParameterInfo.GetCustomAttributes(true).Select(s => s.GetType().Name).ToList();
            }
            var isSensitiveData = attr.Where(s => s == "SensitiveDataAttribute").Any();
            if (!isSensitiveData)
            {
                return;
            }
            //设置为string类型
            parameter.Schema.Type = "string";
            parameter.Description = "【脱敏数据】" + parameter.Description;
        }
    }
}
